<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="central/include :: header('物料录入')" />
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-centralMaterial-add">
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">物料唯一编码：</label>
            <div class="col-sm-8">
                <div class="row" style="padding: 0px 15px;">
                    <input name="id" class="form-control col-sm-9" style="width: 75%;display: inline-block;" type="text" required>
                    <span class="col-sm-3">
                        <button type="button" onclick="generateSerialNumber($('[name=id]'))" class="btn btn-success">生成流水号</button>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">物料批次号：</label>
            <div class="col-sm-8">
                <select name="batchNo" class="form-control m-b col-sm-9" onchange="batchNoChange(this)"  style="width: 75%;display: inline-block;" required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">物料类型：</label>
            <div class="col-sm-8">
                <select name="typeId" onchange="typeIdChange(this)" class="form-control m-b" required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">初始操作站点：</label>
            <div class="col-sm-8">
                <select name="operationStationId" class="form-control m-b" required>
                    <option value="">请先选择物料类型</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">合成物料：</label>
            <div class="col-sm-8">
                <select name="parentTypeId" onchange="parentTypeIdChange(this)" class="form-control m-b" required>
                    <option value="">请先选择物料类型</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label  class="col-sm-3 control-label is-required">所需子物料列表：</label>
            <div class="col-sm-8" style="padding: 0px;">
                <input name="childMaterialIds" class="form-control" type="text" readonly required>
                <div class="col-sm-12 select-table table-striped">
                    <table id="bootstrap-table-1"></table>
                </div>
            </div>
        </div>
        <!--       物料所属的根产品类     -->
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">物料所属：</label>
            <div class="col-sm-8">
                <select name="productTypeId" class="form-control m-b" required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">工艺编号：</label>
            <div class="col-sm-8">
                <select name="artProcessId" class="form-control m-b" required>
                    <option value="">请先选择物料类型</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">描述：</label>
            <div class="col-sm-8">
                <textarea name="remark" class="form-control"></textarea>
            </div>
        </div>
    </form>
</div>
<th:block th:include="central/include :: footer" />
<th:block th:include="include :: import-js('serialNumber')"/>
<th:block th:include="central/include :: import-js('centralProduct')"/>
<th:block th:include="central/include :: import-js('centralArtProcess')"/>
<th:block th:include="central/include :: import-js('centralProductTypeOperationStation')"/>
<script th:inline="javascript">

    var prefix = ctx + "central/centralMaterial"
    var materialStatusDatas = [[${@dict.getType('central_material_status')}]];
    const batchNoSetOfSyntheticMaterial = new Set();
    const materialTypeListOfPartMap = new Map();

    $("#form-centralMaterial-add").validate({
        focusCleanup: true
    });

    function generateSerialNumber($input){
        $.serialNumberBusiness.openGenerateSerialNumber(serialNumber=>{
            $input.val(serialNumber)
        })
    }

    /**/
    $(function(){
        loadMaterialBatchNoData();

        //loadMaterialListOfSyntheticProduct();

        loadMaterialListOfFinishedProduct();
    })

    /*加载产品物料列表*/
    function loadMaterialListOfFinishedProduct(){
        $.productTypeBusiness.getSimpleListOfFinishedProduct("[name=productTypeId]")
    }

    /*加载物料批次号列表*/
    function loadMaterialBatchNoData(){
        const $batchNo = $("[name=batchNo]")
        $.materialBusiness.getDistinctMaterialBatchNoList({$select:$batchNo},null,res=>{
            loadDataForBatchNo()
        })
    }

    function loadDataForBatchNo(){
        const batchNo = $("[name=batchNo]").val()
        const $productTypeId = $("[name=productTypeId]")
        $.centralProductBusiness.findRoot(batchNo,$.productMaterialTypeBusiness.materialType.SEMI_FINISHED_PRODUCT)
            .then(res=>{
                if(res.data){
                    const data = res.data
                    const productTypeId = data.typeId
                    const productTypes = data.productTypes

                    $.selectComponent.selected({$select:$productTypeId,selectValue:productTypeId})

                    if(productTypes && Array.isArray(productTypes)){
                        $.selectComponent.init({$select:$("[name=typeId]"),data:productTypes,name:'name',value:'id',cache:false})
                    }

                    $productTypeId.attr("readonly",true)
                }else{
                    $productTypeId.attr("readonly",false)
                }
            })
    }

    /*加载半成品物料列表*/
    function loadMaterialListOfSyntheticProduct(){
        $.productTypeBusiness.getSemiFinishedProductSimpleList("[name=typeId]",null,res=>{
            const result = res.data
            console.log("result",result)

            materialTypeListOfPartMap.clear()

            if(result && result instanceof Array){
                result.forEach((item)=>materialTypeListOfPartMap.set(item.id,item))
            }

        })

    }

    function batchNoChange(_this){
        console.log("_this",_this)
        loadDataForBatchNo()
        const batchNo = $(_this).val();
        const typeId = $("[name=typeId]").val()
        if(batchNo && typeId){
            $.table.search()
        }
    }
    function typeIdChange(_this){
        console.log("_this",_this)
        const typeId = $(_this).val();
        const batchNo = $("[name=batchNo]").val()
        const $artProcessId = $('[name=artProcessId]');
        const $operationStationId = $('[name=operationStationId]');
        if(typeId){
            $.artProcessBusiness.getSimpleListByProductTypeId({$select:$artProcessId,fillDefault:false},typeId)
            $.productTypeOperationStationBusiness.getListByProductTypeId({$select:$operationStationId,fillDefault:false},typeId)
            getParentMaterialTypeList(typeId)
            if(batchNo){
                $.table.search()
            }
        }else{
            $artProcessId.empty()
            $artProcessId.append('<option value="">请先选择物料类型</option>')

            $operationStationId.empty()
            $operationStationId.append('<option value="">请先选择物料类型</option>')

            const $parentTypeId = $("[name=parentTypeId]")
            $parentTypeId.empty()
            $parentTypeId.append('<option value="">请先选择物料类型</option>')
        }
    }
    //获取父级物料类型
    function getParentMaterialTypeList(materialTypeId){
        $.productTypeBusiness.getParentMaterialTypeList({$select:$("[name=parentTypeId]"),fillDefault:false,name:'name',value:'id'},materialTypeId)
    }

    function submitHandler() {
        if ($.validate.form()) {
            const data = $.common.formToJSON()
            console.log("data",data,batchNoSetOfSyntheticMaterial)
            data.childMaterialIds = Array.from(batchNoSetOfSyntheticMaterial)
            console.log("data==",data,batchNoSetOfSyntheticMaterial)
            $.operation.insert(prefix, data);
        }
    }
    function queryParams(params){
        table.set();
        const curParams = {
            // 传递参数查询参数
            pageSize:       params.limit,
            pageNum:        params.offset / params.limit + 1,
            searchValue:    params.search,
            orderByColumn:  params.sort?(table.options.sortPrefix+params.sort):"",
            isAsc:          params.order
        };
        const fixedParams = {
            state:1,
            batchNo: $('[name=batchNo]').val(),
            parentTypeId: $('[name=typeId]').val()
        }
        return $.extend(curParams, fixedParams);
    }

    function updateForChildMaterialIds(){
        console.log(batchNoSetOfSyntheticMaterial,"batchNoSetOfSyntheticMaterial")
        $("[name=childMaterialIds]").val([...batchNoSetOfSyntheticMaterial])
    }
    $(function(){
        initChildMaterialTable()
    })
    function initChildMaterialTable(){
        var options = {
            requestPrefix: ctx + "central/centralMaterial",
            uniqueId:'id',
            id:'bootstrap-table-1',
            modalName: "物料",
            signName: "top_central_material",
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            queryParams:queryParams,
            onCheck:function(row, $element){
                batchNoSetOfSyntheticMaterial.add(row.id)
                updateForChildMaterialIds()
            },
            onUncheck:function(row, $element){
                batchNoSetOfSyntheticMaterial.delete(row.id)
                updateForChildMaterialIds()
            },onCheckAll:function(rowsAfter, rowsBefore){
                if(batchNoSetOfSyntheticMaterial.size || rowsAfter.length>1){
                    rowsAfter.forEach(item=>batchNoSetOfSyntheticMaterial.add(item.id))
                }else{
                    batchNoSetOfSyntheticMaterial.add(rowsAfter[0].id)
                }
                updateForChildMaterialIds()
            },onUncheckAll:function(rowsAfter, rowsBefore){
                batchNoSetOfSyntheticMaterial.clear()
                updateForChildMaterialIds()
            },
            columns: [{
                checkbox: true
            },
                {
                    field: 'id',
                    title: '编号',
                    visible: true,
                    sortable:true,
                },
                {
                    field: 'batchNo',
                    title: '物料批次号',
                    sortable:true,
                    formatter: function(value,row,index){
                        return $.table.tooltip(value);
                    }
                },
                {
                    field: 'typeId',
                    title: '物料类型名称',
                    sortable:true,
                    formatter: function(value,row,index){
                        return $.table.tooltip($.common.getItemField(row.materialType,'name'));
                    }
                },
                {
                    field: 'parentTypeId',
                    title: '合成物料名称',
                    sortable:true,
                    formatter: function(value,row,index){
                        return $.table.tooltip($.common.getItemField(row.parentMaterialType,'name'));
                    }
                },
                {
                    field: 'materialStatus',
                    title: '物料状态',
                    sortable:true,
                    formatter: function(value,row,index){
                        return $.table.selectDictLabel(materialStatusDatas,value);
                    }
                }]
        };
        $.table.init(options);
    }

</script>
</body>
</html>